package org.example.frw.data.redis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;

/**
 * Created by wangding on 23/02/2017.
 */
@Configuration
public class RedisConfiguration {

    @Value("${spring.data.redis.host}")
    private String host;

    @Value("${spring.data.redis.port}")
    private Integer port;

    @Value("${spring.data.redis.database}")
    private Integer database;

    //@Value("${spring.data.redis.password}")
    //private String password;

    @Value("${spring.data.redis.lettuce.pool.max-active}")
    private Integer maxActive;

    @Value("${spring.data.redis.lettuce.pool.max-wait}")
    private Integer maxWait;

    @Value("${spring.data.redis.lettuce.pool.max-idle}")
    private Integer maxIdle;

    @Value("${spring.data.redis.lettuce.pool.min-idle}")
    private Integer minIdle;

    @Value("${spring.data.redis.timeout:5}")
    private Integer timeout;

    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration serverConfig = new RedisStandaloneConfiguration(host, port);
        serverConfig.setDatabase(database);
        /*if (StrUtil.isNotBlank(password)) {
            serverConfig.setPassword(password);
        }*/

        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMaxWaitMillis(maxWait);

        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder clientConfigBuilder = LettucePoolingClientConfiguration.builder();
        if (timeout != null) {
            clientConfigBuilder.commandTimeout(Duration.ofMillis(timeout));
        }
        clientConfigBuilder.poolConfig(poolConfig);

        return new LettuceConnectionFactory(serverConfig, clientConfigBuilder.build());
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, String> redisTemplate = new StringRedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

}
